import request from "../../common/utils/request";
import utils from "../../common/utils/utils";
import { getAppMenu, getUserMenu } from "../../router/generate_route";
import BUTTON_PERMISSION from "../../common/utils/buttonPermission";
import { toRaw } from "vue";
import BLCOMMON from "bl-common-vue3";
import RouteUtils from "../../router/router.utils";
import { message } from "ant-design-vue";
import store from "../index";

const user = {
  state: {
    userInfo: {}, // 用户信息
    orgInfo: {}, //菜单顶部企业信息
    buildingInfo: {}, // 楼宇选中情况
    allBuildings: [], // 楼宇集合
    showBuildingCheck: false, // 显隐楼宇弹窗
    homePage: {}, // 首页信息
    menuList: [], // 后端返回的菜单（未处理过的）
    menuNameList: [], // 所有菜单的标识集合（用于权限管理）
    userMenu: [], // 系统菜单(左侧一级菜单)
    hideMenu: [], // 设置信息
    appMenu: [], // 应用归类后的菜单
    settingMenu: [], // 点击设置后展示的子菜单（也算顶级菜单）
    menuPermisson: [], // 非后端返回的菜单比后端返回菜单的关联
    loadedApps: [], // 已经加载过的子应用
    currentAppName: "", //  当前显示的子应用名称
    appViewHeight: 0, // 装载子应用的容器高度
    dictionary: {}, // 命名字典
    watermarkStr: "",
    appList: [], // 左侧应用菜单
    resizeTrigger: 0,
    iframeMenus: [],
    token: "", // token信息
    mainAppInfo: {},
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_BUILDING_INFO: (state, buildingInfo) => {
      state.buildingInfo = { ...state.buildingInfo, ...buildingInfo };
    },
    SET_BUILDINGS: (state, buildings) => {
      state.allBuildings = buildings;
    },
    SET_BUILDINGS_VISIBLE: (state, visible) => {
      state.showBuildingCheck = visible;
    },
    SET_ORGINFO: (state, orgInfo) => {
      state.orgInfo = orgInfo;
      if (orgInfo.dictionary) {
        state.dictionary = { ...orgInfo.dictionary };
        BLCOMMON.utils.setDictionary(toRaw(state.dictionary));
      }
    },
    SET_HOMEPAGE: (state, homePage) => {
      state.homePage = homePage;
    },
    SET_SETTING_MENU: (state, menu) => {
      state.settingMenu = menu;
    },
    SET_MENULIST: (state, list) => {
      state.menuList = list;
    },
    SET_MENU_NAME_LIST: (state, list) => {
      state.menuNameList = list;
    },
    SET_USERMENU: (state, menu) => {
      state.userMenu = menu;
    },
    SET_HIDE_MENU: (state, hideMenu) => {
      state.hideMenu = hideMenu;
    },
    SET_APPMENU: (state, menu) => {
      state.appMenu = menu;
    },

    SET_LOADED_APP: (state, app) => {
      state.loadedApps.push(app);
    },
    CLEAR_LOADED_APP: (state) => {
      state.loadedApps = [];
    },
    SET_CURRENT_APP_NAME: (state, name) => {
      state.currentAppName = name;
    },
    SET_APPVIEW_HEIGHT: (state, height) => {
      state.appViewHeight = height;
    },
    SET_WATERMARK_STR: (state, str) => {
      state.watermarkStr = str;
    },
    SET_APP_LIST: (state, list) => {
      state.appList = list;
    },
    SET_RESIZE_CHANGE: (state) => {
      state.resizeTrigger++;
    },
    SET_MENU_PERMISSON: (state, info) => {
      state.menuPermisson = info;
    },
    SET_IFRAME_MENUS: (state, data) => {
      state.iframeMenus = data;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_MAINAPP_INFO: (state, data) => {
      state.mainAppInfo = data;
    },
  },
  actions: {
    /**
     * @description: 获取user-token
     * @param {Object} data 接口、token等登录信息
     */
    UserLogin({ commit }, data) {
      const { server = "/user", url = "/login/reg", params = {} } = data;
      return new Promise((resolve, reject) => {
        request
          .post(server, url, params)
          .then((res) => {
            // 存入缓存
            if (res && res.token) {
              utils.setStorage("user_token", res.token);
            }
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /**
     * @description: 获取org_token
     * @param {Object} data 接口、token等登录信息
     */
    GetProfile({ commit, getters }) {
      return new Promise((resolve, reject) => {
        request
          .post("/org", "/user/profile", {})
          .then((res) => {
            // 存储或更新token
            utils.setStorage("org_token", res.token);
            BUTTON_PERMISSION.setButtonPermission(res.menu);
            let iframePages = res.menu.filter(
              (v) => v.url_type === "frame_url"
            );
            commit("SET_IFRAME_MENUS", iframePages);
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /**
     * @description: 登出
     */
    Logout() {
      const hide = message.loading("即将跳转登录...", 0);
      const org_token = shareds.getStorage("org_token");
      const goNext = () => {
        shareds.clearStorage();
        shareds.clearCookie("sso_referer");
        setTimeout(() => {
          location.reload();
        }, 400);
      };
      if (!org_token) {
        hide();
        goNext();
      }
      request
        .get("/org", "/user/logout", {})
        .then((res) => {
          hide();
          goNext();
        })
        .catch((err) => {
          hide();
        });
    },
    /**
     * @description: 获取用户信息和展示菜单
     */
    GetUserInfo({ commit, getters }) {
      return new Promise((resolve, reject) => {
        request
          .post("/org", "/user/profile")
          .then((res) => {
            let menuList = res.menu;
            if (store.getters.basicConfig.oem_org_id) {
              menuList = res.menu.filter((item) => item.alias != "getHelp");
            }
            // 存储或更新token
            utils.setStorage("org_token", res.token);
            // 按钮权限
            BUTTON_PERMISSION.setButtonPermission(menuList);

            let iframePages = menuList.filter(
              (v) => v.url_type === "frame_url"
            );
            commit("SET_IFRAME_MENUS", iframePages);

            // 存储个人信息
            commit("SET_USERINFO", res.user_info);
            commit("SET_ORGINFO", res.org_info);

            // 存储返回的菜单信息
            commit("SET_MENULIST", menuList);
            // 展示的子应用菜单
            if (res.appMenuList && res.appMenuList.length) {
              commit("SET_APP_LIST", res.appMenuList);
            }
            // 获取 展示菜单、隐藏菜单、首页 和 所有菜单名称
            const { userMenu, hideMenu, homePage, menuNameList } = getUserMenu(
              menuList,
              res.org_info.dictionary || {}
            );
            const appMenu = getAppMenu(menuList);
            commit("SET_HOMEPAGE", homePage);
            commit("SET_HIDE_MENU", hideMenu);
            commit("SET_USERMENU", userMenu);
            commit("SET_APPMENU", appMenu);
            commit("SET_MENU_NAME_LIST", menuNameList);

            resolve(res);

            // 选中楼宇信息
            commit("SET_BUILDING_INFO", {
              checkedBuildingCount: res.org_info.checked_village_count || 0,
              permissionBuildings: res.checkedBuild,
              checkedBuildings: res.last_build_set,
              villageType:
                res.checkedBuild[0] && res.checkedBuild[0].type
                  ? res.checkedBuild[0].type
                  : res?.org_info?.village_type || null,
            });

            // 设置菜单
            const settingMenu = hideMenu.find(
              (item) => item.alias == "setting"
            );
            if (
              settingMenu &&
              settingMenu.children &&
              settingMenu.children.length
            ) {
              commit("SET_SETTING_MENU", settingMenu.children);
            }

            // 整理菜单权限关联
            RouteUtils.handleMenuPermisson();

          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    SetMainAppProps({ commit }, props) {
      return new Promise((resolve) => {
        commit("SET_MAINAPP_INFO", props);
        commit("SET_USERINFO", props.userInfo);
        commit("SET_ORGINFO", props.orgInfo);
        commit("SET_BUILDING_INFO", props.buildingInfo);
        commit("SET_USERMENU", props.userMenu);
        commit("SET_MENULIST", props.menuList);
        commit("SET_APP_LIST", props.appList);
        let tableConfig = props.tableConfig || {};
        if (tableConfig?.isZebra) {
          document.documentElement.style.setProperty(
            "--zebraColor",
            tableConfig.zebraColor
          );
        } else {
          document.documentElement.style.setProperty("--zebraColor", "#fff");
        }
        document.documentElement.style.setProperty(
          "--tableContentSize",
          tableConfig.tableContentSize
        );
        document.documentElement.style.setProperty(
          "--tableTitleSize",
          tableConfig.tableTitleSize
        );
        document.documentElement.style.setProperty(
          "--tableHeaderSize",
          tableConfig.tableHeaderSize
        );
        store.dispatch("SetTableConfig", tableConfig);
        store.dispatch("setConfig", props.configRes);
        store.dispatch("setIsMobile", props.isMobile);
        store.dispatch("setIsIframe", props.isIframe);
        resolve(props);
      });
    },

    SetToken({ commit }, token) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", token);
        resolve();
      });
    },
    SetMenuPermisson: ({ commit }, info) => {
      commit("SET_MENU_PERMISSON", info);
    },
    SetWatermarkStr({ commit, state }, str) {
      str = str || state.watermarkStr;
      commit("SET_WATERMARK_STR", str);
    },
    SetResizeChange({ dispatch, commit }) {
      commit("SET_RESIZE_CHANGE");
      dispatch("SetWatermarkStr");
    },
    /**
     * @description: 设置已选楼宇
     * @param {*} count
     */
    SetBuildingInfo({ commit }, data) {
      commit("SET_BUILDING_INFO", data);
    },

    SetBuildingVisible({ commit }, visible) {
      commit("SET_BUILDINGS_VISIBLE", visible);
    },

    /**
     * @description: 添加子应用到已加载列表中
     * @param {*} commit
     * @param {*} app
     */
    SetLoadedApp({ commit }, app) {
      commit("SET_LOADED_APP", app);
    },
    ClearLoadedApp({ commit }) {
      commit("CLEAR_LOADED_APP");
    },
    /**
     * @description: 当前显示的子应用名称
     */
    SetCurrentAppName({ commit }, name) {
      commit("SET_CURRENT_APP_NAME", name);
    },
    /**
     * @description: 存储子应用装载容器高度
     * @param {*} commit
     * @param {*} app
     */
    SetAppViewHeight({ commit }, height) {
      commit("SET_APPVIEW_HEIGHT", height);
    },
    SetAllBuildings({ commit }, buildings) {
      commit("SET_BUILDINGS", buildings);
    },
  },
};

export default user;
